//
//  SubscribeListener.swift
//  uwantgoeasy
//
//  Created by 冯传宝 on 12/11/15.
//  Copyright © 2015 uwantsoft. All rights reserved.
//

import Foundation

public class SubscribeListener {
    private var goEasy:GoEasy?
    private var encoder:GoEasyMessageEncoder = GoEasyMessageEncoder()
    
    public init(){}
    final func onSubscriberResult(subscribeResult: SubscribeResult){
        if(MessageCode.OK.rawValue == subscribeResult._resultCode){
            onSuccess()
        }else if(MessageCode.UNAUTHORIZED.rawValue == subscribeResult._resultCode){
            onFailed(GoEasyError(code: 401,content: "Unauthorized"))
        }else if(MessageCode.INTERNAL_ERROR.rawValue == subscribeResult._resultCode){
            onFailed(GoEasyError(code: 500,content: "Internal server error"))
        }
    }
    
    final func onReceivedPushMessage(push:Push){
        if(push.isAckRequired){
            print("ack message...")
            let ack = Ack(sid: goEasy!._sid, id: push._id, executorNumber: push.executorNumber)
            let ackBytes:[UInt8] = encoder.encode(ack)
            goEasy?._socketListener.messageSender?.send(ackBytes)
        }
        let goEasyClientMessage = GoEasyClientMessage(channel: push._channel,content: push._content)
        onMessage(goEasyClientMessage)
    }
    
    public func onMessage(clientMessage: GoEasyClientMessage){
        
    }
    
    public func onSuccess(){
            
    }
    
    public func onFailed(error: GoEasyError){
        
    }

    func setGoEasy(goEasy:GoEasy){
        self.goEasy = goEasy
    }
}